package com.example.movie.ui.user.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.example.movie.R
import com.example.movie.common.constants.AppConstants
import com.example.movie.common.constants.Constants
import com.example.movie.data.user.model.vo.OrderVo
import com.example.movie.utils.RequestUtil
import com.example.movie.utils.SizeUtil
import com.example.movie.utils.ToastUtil
import com.hjq.permissions.OnPermission
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import kotlinx.android.synthetic.main.item_order.view.*
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream


class OrderAdapter(private val items: MutableList<OrderVo>) :
    RecyclerView.Adapter<OrderAdapter.MyViewHolder>() {

    class MyViewHolder(view: View) :
        RecyclerView.ViewHolder(view)

    private val oid2Idx = mutableMapOf<Long, Int>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_order, parent, false)
        )
    }

    override fun getItemCount() = items.size

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        with(holder.itemView) {
            items[position].apply {
                movie_name.text = movieName
                play_time.text = "$playDay $playTimeName "
                agent_info.text = "$agentName $hallName"
                left_time.text = leftTime
                order_state.text = "订单状态: $state"
                orders.text = "座位：" + tickets?.joinToString(separator = " ")
                order_id.text = "订单号: $orderId"
                total_count.text = "订单金额: " + totalMoney.toString() + "元"

                //记录订单和索引的下标对应关系
                this@OrderAdapter.oid2Idx[orderId] = position

                when(state){
                    Constants.OrderState.NOT_GET -> {
                        //加载取票二维码,需要用户认证
                        val cookie = RequestUtil.getAuthenticationCookie()
                        Log.e("", "onBindViewHolder:$cookie")
                        val authUrl =
                            GlideUrl(
                                AppConstants.BASIC_REQUEST_URL + "QRCode?orderId=${orderId}&random=${Math.random()}",
                                LazyHeaders.Builder().addHeader("Cookie", cookie).build()
                            )

                        Glide
                            .with(context)
                            .load(authUrl)
                            .placeholder(R.mipmap.logo)
                            .error(R.drawable.error)
                            .into(QR_code)

                        save_QE_to_album.setOnClickListener {
                            XXPermissions
                                .with(context)
                                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                                .request(object : OnPermission {
                                    override fun hasPermission(granted: MutableList<String>?, all: Boolean) {
                                        if (all) {
                                            QR_code.isDrawingCacheEnabled = true
                                            QR_code.buildDrawingCache(true)
                                            val drawingCache = QR_code.drawingCache
                                            saveQrCodeToAlbum(context, drawingCache,orderId)
                                        }
                                    }

                                    override fun noPermission(denied: MutableList<String>?, never: Boolean) {
                                        if (never) {
                                            ToastUtil.toast(context, "被拒绝授权，请主动申请授读写外部存储权限");
                                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                            XXPermissions.startPermissionActivity(context, denied);
                                        }
                                    }
                                })

                        }
                    }
                    Constants.OrderState.SUCCESS -> {
                        save_QE_to_album.visibility = View.GONE
                        val layoutParams = QR_code.layoutParams
                        layoutParams.width = SizeUtil.dip2px(context, 50f)
                        layoutParams.height = SizeUtil.dip2px(context, 50f)
                        QR_code.layoutParams = layoutParams
                        QR_code.setImageResource(R.drawable.success)
                    }
                    Constants.OrderState.EXPIRED -> {
                        left_time_info.visibility = View.GONE
                        left_time.visibility = View.GONE
                        changing_date.visibility = View.GONE
                        save_QE_to_album.visibility = View.GONE
                        val layoutParams = QR_code.layoutParams
                        layoutParams.width = SizeUtil.dip2px(context, 50f)
                        layoutParams.height = SizeUtil.dip2px(context, 50f)
                        QR_code.layoutParams = layoutParams
                        QR_code.setImageResource(R.drawable.expire)
                    }
                }

            }

        }

    }

    private fun saveQrCodeToAlbum(context: Context?, bmp: Bitmap, orderId: Long) {
        // 首先保存图片 创建文件夹
        val appDir = File(Environment.getExternalStorageDirectory(), "shy")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        //图片文件名称
        val fileName = "shy_$orderId.jpg"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
            return
        }
        // 其次把文件插入到系统图库
        val path: String = file.absolutePath
        try {
            MediaStore.Images.Media.insertImage(context!!.contentResolver, path, fileName, null)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
            return
        }
        //删除临时文件
        file.delete()
        // 最后通知图库更新
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val uri: Uri = Uri.fromFile(file)
        intent.data = uri
        context!!.sendBroadcast(intent)
        Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show()
    }


    fun removeSuccessOrder(orderId: Long) {
        oid2Idx[orderId]?.let {
            items.removeAt(it)
            notifyItemRemoved(it)
            updateIndexMap(orderId)
            oid2Idx.remove(orderId)
        }
    }

    private fun updateIndexMap(oid: Long) {
        var flag = false
        for (entry in oid2Idx.entries) {
            if (flag) {
                entry.setValue(entry.value.dec())
            } else if (entry.key == oid) {
                flag = true
            }
        }
    }


}